<template>
  <el-card class="profile-container">
    <template #header>
      <h3>个人资料</h3>
    </template>
    
    <el-form 
      :model="profileForm" 
      label-width="100px"
      :rules="rules"
      ref="profileFormRef"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="profileForm.username" disabled />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="profileForm.email" disabled />
      </el-form-item>
      
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="/api/upload/avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserProfile, updateUserProfile } from '@/api/user'
import { Plus } from '@element-plus/icons-vue'

const profileForm = ref({
  username: '',
  email: '',
  avatar: ''
})

const profileFormRef = ref(null)

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const loadProfile = async () => {
  try {
    const res = await getUserProfile()
    profileForm.value = res.data
  } catch (error) {
    console.error('获取个人资料失败:', error)
  }
}

const handleAvatarSuccess = (response) => {
  profileForm.value.avatar = response.url
}

const submitForm = async () => {
  try {
    await profileFormRef.value.validate()
    await updateUserProfile(profileForm.value)
    ElMessage.success('个人资料更新成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新个人资料失败:', error)
      ElMessage.error(error.message || '更新个人资料失败')
    }
  }
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.profile-container {
  min-height: 500px;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>